package io.gps.datatransfer.command;

import io.gps.datatransfer.utils.ByteUtils;
import org.apache.log4j.Logger;
import org.apache.mina.core.buffer.IoBuffer;

/**
 * 上行指令封包
 * @author rxw
 *
 */
public class UpMessage {
	private static Logger logger = Logger.getLogger(UpMessage.class);
	/**
	 * 消息ID
	 */
	int messageID;
	/**
	 * 消息分包项
	 */
	int splitPack;
	/**
	 * 是否RSA加密
	 */
	int encrypt;
	/**
	 * 消息体长度
	 */
	int msgLen;
	/**
	 * sim卡号
	 */
	String telphone;

	/**
	 * 消息流水号
	 */
	int msgSeri;
	/**
	 * 消息分包总包数
	 */
	int packSum;
	/**
	 * 消息分包序号
	 */
	int packSn;
	/**
	 * 验证码
	 */
	int checkCode;
	IoBuffer messageBody;
	public Object bodyObj="";
	public UpMessage(IoBuffer src) throws Exception{

		IoBuffer data = IoBuffer.allocate(src.limit()-2);
		data.put(src.array(),1,src.limit()-2);
		data.flip();
		IoBuffer buf = IoBuffer.allocate(15);
		buf.setAutoExpand(true);
		byte b= data.get();
		buf.put(b);
		//转义同时计算校验码
		int tempcheckcode=b;
		while(data.hasRemaining()){
			b = data.get();
			if(b==0x7d&&data.hasRemaining()){
				b = data.get();
				if(b==0x02){
					b=(byte)0x7e;
					buf.put(b);
					tempcheckcode ^= b;
					continue;
				}else if(b==0x01){
					b=(byte)0x7d;
					buf.put(b);
					tempcheckcode ^= b;
					continue;
				}else{
					throw new Exception("非法信息");
				}
			}else{
				buf.put(b);
				tempcheckcode ^= b;
			}
		}
		int sendcheck=b;
		tempcheckcode^= sendcheck;
		//计算出的校验码的实际得到的检验码不一致抛出异常
		if(sendcheck!=tempcheckcode){
			throw new Exception("非法信息");
		}

		buf.shrink();  //释放无用资源
		buf.flip();
		messageID = buf.getUnsignedShort();
		//得到消息属性部分原始数据
		int mlen=buf.getUnsignedShort();
		if((mlen&8192)==8192){
			splitPack=1;//分包
		}else{
			splitPack=0;//不分包
		}
		//把原始数据右移10位 & 7 得到加密状态部分数据信息
		encrypt=(mlen>>>10)&0x7;
		msgLen = mlen&0x3FF;//获得数据长度
		StringBuilder telphone = new StringBuilder();
		for(int i = 0;i<6;i++){
			telphone.append(ByteUtils.decodeBCD(buf.getUnsigned()));
		}
		this.telphone=telphone.toString();

		msgSeri=buf.getUnsignedShort();
		if(splitPack==1){
			packSum=buf.getUnsignedShort();
			packSn=buf.getUnsignedShort();
		}

		IoBuffer msgbuf = IoBuffer.allocate(msgLen);
		byte[] tempbyte=new byte[msgLen];
		buf.get(tempbyte);
		msgbuf.put(tempbyte);
		msgbuf.flip();
		messageBody=msgbuf;
	}

	public int getMessageID() {
		return messageID;
	}
	public int getSplitPack() {
		return splitPack;
	}
	public int getEncrypt() {
		return encrypt;
	}
	public int getMsgLen() {
		return msgLen;
	}
	public String getTelphone() {
		return telphone;
	}
	public int getMsgSeri() {
		return msgSeri;
	}
	public int getPackSum() {
		return packSum;
	}
	public int getPackSn() {
		return packSn;
	}
	public int getCheckCode() {
		return checkCode;
	}
	public IoBuffer getMessageBody() {
		return messageBody;
	}
	
}
